<!DOCTYPE html>
<html>
<head>
    <title>类型配置</title>
    <#include "/header.html">
    <link
            href="${request.contextPath}/statics/plugins/jquery-layout/jquery.layout-latest.css"
            rel="stylesheet" />
    <link
            href="${request.contextPath}/statics/css/bootstrapZtree.css"
            rel="stylesheet" />



</head>
<body>


<div id="rrapp" v-cloak class="container-div ui-layout-center">
    <div v-show="showList">
        <!--<span id="directory" class="switch-on"></span>-->
        <div class="grid-btn">
            <div class="form-group col-sm-2">
                <input type="text" class="form-control" v-model="q.cateName"
                       @keyup.enter="query" placeholder="类型名称">
            </div>
            <a class="btn btn-default" @click="query">查询</a>
           <a class="btn btn-primary" @click="add"><i class="fa fa-plus"></i>&nbsp;新增</a>
           <a class="btn btn-primary" @click="update"><i class="fa fa-pencil-square-o"></i>&nbsp;修改</a>
           <a class="btn btn-danger" @click="del"><i class="fa fa-trash-o"></i>&nbsp;删除</a>
</div>


<div class="col-sm-12 select-info table-striped">
    <table id="bootstrap-table" data-mobile-responsive="true"></table>
</div>
</div>

<div v-show="!showList" class="panel panel-default"  >
    <div class="panel-heading">{{title}}</div>
    <form class="form-horizontal" id="form">
        <div class="form-group">
            <div class="col-sm-2 control-label">类型KEY</div>
            <div class="col-sm-10">
                <input type="text" class="form-control" v-model="user.cateKey"
                       placeholder="类型KEY">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-2 control-label">类型名称</div>
            <div class="col-sm-10">
                <input type="text" class="form-control" v-model="user.cateName"
                       placeholder="类型名称">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-2 control-label">统计字段</div>
            <div class="col-sm-10">
                <input type="text" class="form-control" v-model="user.queryFiled"
                       placeholder="统计字段">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-2 control-label"></div>
            <input type="button" ref="submitBtn" class="btn btn-primary" @click="saveOrUpdate" value="确定"/>
            &nbsp;&nbsp;<input type="button" class="btn btn-warning" @click="reload" value="返回"/>
        </div>
    </form>

</div>

<ul id="treeDemo" class="ztree"></ul>
</div>


<script
        src="${request.contextPath}/statics/plugins/jquery-layout/jquery.layout-latest.js"></script>

<script
        src="${request.contextPath}/statics/js/zTreeCore.js"></script>
<script
        src="${request.contextPath}/statics/js/zTreeEdit.js"></script>
<script
        src="${request.contextPath}/statics/js/zTreeExcheck.js"></script>
<!-- <script src="${request.contextPath}/statics/js/modules/sys/user.js?_${.now?long}"></script>
-->
<script>


    $(document)
        .ready(
            function() {
                $('body').layout({
                    west__size : 185
                });
                $('#bootstrap-table')
                    .bootstrapTable(
                        {
                            method : 'post', // 服务器数据的请求方式 get or post
                            contentType : "application/json",
                            url : baseURL + 'baiducategory/findBaiduCategoryPage', // 服务器数据的加载地址
                            showRefresh : true,
                            showToggle : true,
                            showColumns : true,
                            //showExport :true,
                            sortable: true,
                            sortName:"userId",// 排序列名称
                            sortOrder: "desc",
                            iconSize : 'outline',
                            toolbar : '#exampleToolbar',
                            striped : true, // 设置为true会有隔行变色效果
                            dataType : "json", // 服务器返回的数据类型
                            pagination : true, // 设置为true会在底部显示分页条
                            // queryParamsType : "limit",
                            // //设置为limit则会发送符合RESTFull格式的参数
                            singleSelect : false, // 设置为true将禁止多选
                            // contentType : "application/x-www-form-urlencoded",
                            // //发送到服务器的数据编码类型
                            pageSize : 10, // 如果设置了分页，每页数据条数
                            pageNumber : 1, // 如果设置了分布，首页页码
                            // search : true, // 是否显示搜索框
                            //showColumns : false, // 是否显示内容下拉框（选择显示的列）
                            sidePagination : "server", // 设置在哪里进行分页，可选值为"client" 或者
                            // "server"
                            queryParams : function(params) {
                                //console.log(params)
                                return {
                                    // 说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,以及所有列的键值对
                                    limit : params.limit,
                                    page : (params.offset/params.limit) + 1,
                                    cateName : vm.q.cateName,
                                    // sidx: params.sort,      //排序列名
                                    //order: params.order //排位命令（desc，asc）
                                    /* sort:"userId",
                                    order:"desc" */
                                };
                            },
                            // //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
                            // queryParamsType = 'limit' ,返回参数必须包含
                            // limit, offset, search, sort, order 否则, 需要包含:
                            // pageSize, pageNumber, searchText, sortName,
                            // sortOrder.
                            // 返回false将会终止请求
                            columns : [
                                {
                                    checkbox : true
                                },
                                {
                                    field : 'cateName',
                                    align:'center',
                                    title : '类型名称'
                                },
                                {
                                    field : 'cateKey',
                                    align:'center',
                                    title : '类型KEY'
                                },
                                {
                                    field : 'queryFiled',
                                    align:'center',
                                    title : '统计字段'
                                },
                                {
                                    field : 'createTime', // 列字段名
                                    align:'center',
                                    title : '创建时间',// 列标题
                                },
                                {
                                    title : '操作',
                                    field : 'id',
                                    width:330,
                                    align : 'center',
                                    formatter : function(
                                        value, row,
                                        index) {
                                        var e = '<a  class="btn btn-primary btn-sm '
                                            + ''
                                            + '" href="#" mce_href="#" title="编辑" onclick="edit(\''
                                            + row.id
                                            + '\')"><i class="fa fa-edit " style="margin-right: 5px"></i>编辑</a> ';
                                        var d = '<a class="btn btn-danger btn-sm '
                                            + ''
                                            + '" href="#" title="删除"  mce_href="#" onclick="remove(\''
                                            + row.id
                                            + '\')"><i class="fa fa-remove" style="margin-right: 5px"></i>删除</a> ';
                                        var f = '<a class="btn btn-success btn-sm '
                                            + ''
                                            + '" href="#" title="绑定"  mce_href="#" onclick="bindSite(\''
                                            + row.id
                                            + '\')"><i class="fa fa-wrench" style="margin-right: 5px"></i>绑定</a> ';
                                        return e + d + f;
                                    }
                                } ]
                        });
            });
   var setting = {
       data:{
           simpleData: {
               enable: true,
               idKey: "id",
               pIdKey: "accountId",
               rootPId: -1
           }
       },

        view: {
            // addHoverDom: addHoverDom,
            // removeHoverDom: removeHoverDom,
            selectedMulti: false
        },
        check: {
            enable: true,
            chkStyle : "checkbox",    //复选框
            chkboxType : {
                "Y" : "ps",
                "N" : "ps"
            }
        },
       callback : {
           beforeClick : beforeClick,
           onCheck : onCheck
       }
   };
    var ztree;
    function beforeClick(treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("siteType");
        zTree.checkNode(treeNode, !treeNode.checked, null, true);
        return false;
    }
    function onCheck(e, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("siteType");
        var nodes = zTree.getCheckedNodes(true);
        //console.log(nodes)
        vm.checkNode = [];
        for (var i = 0, l = nodes.length; i < l; i++) {
            if (!nodes[i].isParent) {       //isParent判断是否为父级，也就是是否有下级
                vm.checkNode.push(nodes[i].id);    //获取所选节点的名称
            }
        }
       // console.log(vm.checkNode)
    }
    var vm = new Vue({
        el : '#rrapp',
        data : {
            q : {
                cateName : ''
            },
            showList : true,
            cateId:'',
            title : null,
            checkNode:[],
            menu:{
                parentName:null,
                parentId:0,
                type:1,
                orderNum:0,
                isAlert:false
            },
            user : {
                cateName:'',
                cateKey:'',
                queryFiled:''
            }
        },
        methods : {
            getMenu: function(id){
                vm.cateId = id;
                $.ajax({
                    type : "POST",
                    async:false,
                    url : baseURL + "baiducategory/findCategoryBindSite",
                    contentType : "application/json",
                    data : JSON.stringify({id:id}),
                    success : function(r) {
                        if (r.code == 0) {
                          var menuList = [];
                            menuList = r.result.accountList.concat(r.result.siteList);
                            //console.log(menuList)
                            ztree = $.fn.zTree.init($("#siteType"), setting, menuList);
                            // var node = ztree.getNodeByParam("id", vm.menu.parentId);
                            // ztree.selectNode(node);
                            var arr = [];
                            var parentArr = [];
                            menuList.map(function (item) {
                                if(arr.indexOf(item.id) == -1){
                                    arr.push(item.id)
                                }
                            });
                            for(var j=0;j< r.result.bindsiteIdList.length;j++){
                                 for(var i=0;i<menuList.length;i++){
                                     if(( r.result.bindsiteIdList[j]==menuList[i].id)&&(parentArr.indexOf(menuList[i].accountId)==-1)){
                                         parentArr.push(menuList[i].accountId);
                                     }

                                }
                            }
                          //  console.log(parentArr);
                          var bindList = [];
                            bindList =  r.result.bindsiteIdList.concat(parentArr);
                            bindList.map(function (item) {
                               if(arr.indexOf(item)!= -1){
                                    ztree.checkNode(ztree.getNodeByParam("id", item), true, false);
                                }
                            });
                            vm.menuTree();
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            },
            query : function() {
                vm.reload();
            },
            add : function() {
                vm.showList = false;
                vm.title = "新增";
                vm.user = {
                    cateName:'',
                    cateKey:'',
                    queryFiled:''
                };
            },
            update : function() {
                // console.log(11111)
                vm.user = {
                    cateName:'',
                    cateKey:'',
                    queryFiled:''
                };
                var userId = getSelectedRow();
                if (userId == null) {
                    return;
                }
                vm.showList = false;
                vm.title = "修改";
                vm.getUser(userId.id);
            },
            del : function() {
                var delArr = [];
                var userIds = getSelectedRows();
                if (userIds == null) {
                    return;
                }
                // console.log(userIds);
                userIds.map(function (item) {
                    delArr.push(item.id)
                });
                // return false;
                confirm('确定要删除选中的记录？', function() {
                    $.ajax({
                        type : "POST",
                        url : baseURL + "baiducategory/deleteBaiduCategory",
                        contentType : "application/json",
                        data : JSON.stringify({id:delArr}),
                        success : function(r) {
                            if (r.code == 0) {
                                alert('操作成功', function() {
                                    vm.reload();
                                });
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                });
            },
            saveOrUpdate : function() {
                var url = vm.user.id == null ? "baiducategory/saveBaiduCategory"
                    : "baiducategory/updateBaiduCategory";
                //console.log(vm.user.platformId);
                var btn = vm.$refs.submitBtn;
                if(checkIsBank(vm.user.cateName) || checkIsBank(vm.user.cateKey) || checkIsBank(vm.user.queryFiled)){
                    alert("类型名称为必填字段!");
                    return false;
                }
                btn.disabled = true;
                $.ajax({
                    type : "POST",
                    url : baseURL + url,
                    contentType : "application/json",
                    data : JSON.stringify(vm.user),
                    success : function(r) {
                        btn.disabled = false;
                        if (r.code === 0) {
                            alert('操作成功', function() {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            },
            getUser : function(id) {
                $.ajax({
                    type : "POST",
                    url : baseURL + "baiducategory/findBaiduCategoryById",
                    contentType : "application/json",
                    data : JSON.stringify({id:id}),
                    success : function(r) {
                        if (r.code === 0) {
                            var data = r.result;
                            vm.user.id = data.id;
                            vm.user.queryFiled = data.queryFiled;
                            vm.user.cateName = data.cateName;
                            vm.user.cateKey = data.cateKey;
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            },
            menuTree: function(){
                layer.open({
                    type: 1,
                    offset: '50px',
                    skin: 'layui-layer-molv',
                    title: "选择站点",
                    area: ['400px', '450px'],
                    shade: 0.7,
                    shadeClose: false,
                    content: jQuery("#siteLayer"),
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        onCheck();
                        var params = {
                            cateId:vm.cateId,
                            siteId:vm.checkNode
                        };
                        //console.log(params);
                        $.ajax({
                            type : "POST",
                            url : baseURL + "baiducategory/bindCateSite",
                            contentType : "application/json",
                            data : JSON.stringify(params),
                            success : function(r) {
                                if (r.code === 0) {
                                    alert('操作成功', function() {
                                        layer.close(index);
                                        vm.reload();
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });


                    }
                });
            },
            reload : function() {
                vm.showList = true;
                // var opt = {
                //     url: baseURL + 'baiducategory/findBaiduCategoryPage',
                //     contentType : "application/json",
                //     silent: true,
                //     query:{
                //         limit : 10,
                //         page : 1,
                //         cateName : vm.q.cateName
                //     }
                // };

                $('#bootstrap-table').bootstrapTable('refresh',
                    {
                        cateName : vm.q.cateName
                    });

            }
        }
    });
    function edit(id) {
        if (id == null) {
            return;
        }
        //console.log(2222)
        vm.user = {
            cateName:'',
            cateKey:'',
            queryFiled:''
         };
        vm.showList = false;
        vm.title = "修改";
        vm.getUser(id);
    }
   function bindSite(id) {
       vm.getMenu(id);
   }
    function remove(id) {
        confirm('确定要删除选中的记录？', function() {
            $.ajax({
                type : "POST",
                url : baseURL + "baiducategory/deleteBaiduCategory",
                contentType : "application/json",
                data : JSON.stringify({id:[id]}),
                success : function(r) {
                    if (r.code == 0) {
                        alert('操作成功', function() {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        });
    }
</script>

<!-- 选择菜单 -->
<div id="siteLayer" style="display: none;padding:10px;">
    <ul id="siteType" class="ztree"></ul>
</div>
</body>
</html>